package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.PageResult;
import com.itheima.dto.QuestionsAuditsDto;
import com.itheima.dto.QuestionsDto;
import com.itheima.dto.QuestionsRecordsDto;
import com.itheima.mapper.*;
import com.itheima.pojo.*;
import com.itheima.service.QuestionsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;


@Service
public class QuestionsServiceImpl implements QuestionsService {

    @Autowired
    private QuestionsMapper questionsMapper;

    @Autowired
    private SubjectsDirectorysMapper subjectsDirectorysMapper;

    @Autowired
    private QuestionsOptionsMapper questionsOptionsMapper;

    @Autowired
    private AnswerMapper answerMapper;

    @Autowired
    private QuestionsAuditsMapper questionsAuditsMapper;

    @Autowired
    private QuestionsRecordsMapper questionsRecordsMapper;

    @Autowired
    private CompanysMapper companysMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private SubjectsMapper subjectsMapper;

    @Autowired
    private SubjectsTagsMapper subjectsTagsMapper;

    @Override
    public PageResult findPage(Integer page, Integer pagesize, QuestionsDto questionsDto) {
        Questions questions = new Questions();
        BeanUtils.copyProperties(questions,questionsDto);
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        IPage<Questions> p = new Page<>(page,pagesize);
        LambdaQueryWrapper<Questions> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(null!=questionsDto.getSubjectID(),Questions::getSubjectID,questionsDto.getSubjectID())
                .eq(null!=questionsDto.getDifficulty(),Questions::getDifficulty,questionsDto.getDifficulty())
                .eq(null!=questionsDto.getQuestionType(),Questions::getQuestionType,questionsDto.getQuestionType())
                .eq(null!=questionsDto.getTags(),Questions::getTags,questionsDto.getTags())
                .eq(null!=questionsDto.getProvince(),Questions::getProvince,questionsDto.getProvince())
                .eq(null!=questionsDto.getCity(),Questions::getCity,questionsDto.getCity())
                .like(null!=questionsDto.getKeyword(),Questions::getQuestion,questionsDto.getKeyword())
                .like(null!=questionsDto.getRemarks(),Questions::getRemarks,questionsDto.getRemarks())
                .eq(null!=questions.getEnterpriseID(),Questions::getEnterpriseID,questions.getEnterpriseID())
                .eq(null!=questionsDto.getDirection(),Questions::getDirection,questionsDto.getDirection())
                .eq(null!=questionsDto.getCreatorID(),Questions::getCreatorID,questionsDto.getCreatorID())
                .eq(null!=questionsDto.getCatalogID(),Questions::getCatalogID,questionsDto.getCatalogID());
        wrapper.eq(Questions::getIsChoice, 0);
        IPage<Questions> questionsIPage = questionsMapper.selectPage(p, wrapper);
        List<Questions> records = questionsIPage.getRecords();
        records.stream().forEach(c->{
            LambdaQueryWrapper<SubjectsDirectorys> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(SubjectsDirectorys::getId,c.getCatalogID());
            SubjectsDirectorys subjectsDirectorys = subjectsDirectorysMapper.selectOne(wrapper1);
            Companys companys = companysMapper.selectById(c.getEnterpriseID());
            Subjects subjects = subjectsMapper.selectById(c.getSubjectID());
            c.setCatalog(subjectsDirectorys.getDirectoryName());
            c.setCreator(user.getUsername());
            c.setEnterprise(companys.getShortName());
            c.setSubject(subjects.getSubjectName());
            c.setChkUser(user.getUsername());
        });
        PageResult pageResult = new PageResult((int)questionsIPage.getTotal(),(int)questionsIPage.getSize(),(int)questionsIPage.getPages(),(int)questionsIPage.getCurrent(),records);
        return pageResult;
    }

    @Transactional
    @Override
    public void deleteById(Integer id) {
        Questions questions = questionsMapper.selectById(id);
        LambdaQueryWrapper<SubjectsDirectorys> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(SubjectsDirectorys::getSubjectID,questions.getSubjectID());
        SubjectsDirectorys subjectsDirectorys = subjectsDirectorysMapper.selectOne(wrapper1);
        subjectsDirectorys.setTotals(subjectsDirectorys.getTotals() - 1);
        Subjects subjects = subjectsMapper.selectById(questions.getSubjectID());
        subjects.setTotals(subjects.getTotals() - 1);
        LambdaQueryWrapper<SubjectsTags> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SubjectsTags::getTagName,questions.getTags());
        SubjectsTags subjectsTags = subjectsTagsMapper.selectOne(wrapper);
        subjectsTags.setTotals(subjectsTags.getTotals() - 1);
        subjectsDirectorysMapper.updateById(subjectsDirectorys);
        subjectsMapper.updateById(subjects);
        subjectsTagsMapper.updateById(subjectsTags);
        questionsMapper.deleteById(id);
    }

    @Transactional
    @Override
    public void insert(Questions questions) {
        questions.setPublishState(0);//0下架 1上架
        questions.setPublishDate(LocalDateTime.now());
        questions.setChkState(0);
        questions.setNumber(UUID.randomUUID().toString());
        SubjectsDirectorys subjectsDirectorys = subjectsDirectorysMapper.selectById(questions.getCatalogID());
        Integer creatorID = subjectsDirectorys.getCreatorID();
        LocalDateTime addDate = subjectsDirectorys.getAddDate();
        subjectsDirectorys.setTotals(subjectsDirectorys.getTotals() + 1);
        questions.setAddDate(addDate);
        questions.setCreatorID(creatorID);
        Subjects subjects = subjectsMapper.selectById(questions.getSubjectID());
        subjects.setTotals(subjects.getTotals() + 1);
        LambdaQueryWrapper<SubjectsTags> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SubjectsTags::getTagName,questions.getTags());
        SubjectsTags subjectsTags = subjectsTagsMapper.selectOne(wrapper);
        subjectsTags.setTotals(subjectsTags.getTotals() + 1);
        subjectsDirectorysMapper.updateById(subjectsDirectorys);
        subjectsMapper.updateById(subjects);
        subjectsTagsMapper.updateById(subjectsTags);
        questionsMapper.insert(questions);
    }

    @Override
    public QuestionsDto findById(Integer id) {
        Questions questions = questionsMapper.selectById(id);
        LambdaQueryWrapper<QuestionsOptions> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuestionsOptions::getQuestionsID,questions.getId());
        List<QuestionsOptions> questionsOptions = questionsOptionsMapper.selectList(wrapper);
        QuestionsDto questionsDto = new QuestionsDto();
        BeanUtils.copyProperties(questions,questionsDto);
        questionsDto.setQuestionsOptions(questionsOptions);
        return questionsDto;
    }

    @Override
    public void updateById(Integer id, QuestionsDto questionsDto) {
        //todo id传来没用
        questionsMapper.updateById(questionsDto);
    }

    @Override
    public void modifyById(Integer id, Integer publishState) {
        Questions questions = new Questions();
        questions.setId(id);
        questions.setPublishState(publishState);
        questionsMapper.updateById(questions);
    }

    @Override
    public PageResult findPageChoice(Integer page, Integer pagesize, QuestionsDto questionsDto) {
        Questions questions = new Questions();
        BeanUtils.copyProperties(questions,questionsDto);
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        IPage<Questions> p = new Page<>(page,pagesize);
        LambdaQueryWrapper<Questions> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(null!=questionsDto.getSubjectID(),Questions::getSubjectID,questionsDto.getSubjectID())
                .eq(null!=questionsDto.getDifficulty(),Questions::getDifficulty,questionsDto.getDifficulty())
                .eq(null!=questionsDto.getQuestionType(),Questions::getQuestionType,questionsDto.getQuestionType())
                .eq(null!=questionsDto.getTags(),Questions::getTags,questionsDto.getTags())
                .eq(null!=questionsDto.getProvince(),Questions::getProvince,questionsDto.getProvince())
                .eq(null!=questionsDto.getCity(),Questions::getCity,questionsDto.getCity())
                .like(null!=questionsDto.getKeyword(),Questions::getQuestion,questionsDto.getKeyword())
                .like(null!=questionsDto.getRemarks(),Questions::getRemarks,questionsDto.getRemarks())
                .eq(null!=questions.getEnterpriseID(),Questions::getEnterpriseID,questions.getEnterpriseID())
                .eq(null!=questionsDto.getDirection(),Questions::getDirection,questionsDto.getDirection())
                .eq(null!=questionsDto.getCreatorID(),Questions::getCreatorID,questionsDto.getCreatorID())
                .eq(null!=questionsDto.getCatalogID(),Questions::getCatalogID,questionsDto.getCatalogID())
                .eq(null!=questionsDto.getChkState(),Questions::getChkState,questionsDto.getChkState());
        String shortName = questionsDto.getShortName();
        if (shortName != null) {
            LambdaQueryWrapper<Companys> wrpper3 = new LambdaQueryWrapper<>();
            wrpper3.eq(Companys::getShortName, shortName);
            Companys company = companysMapper.selectOne(wrpper3);
            wrapper.eq(Questions::getEnterpriseID, company.getId());
        }
        wrapper.eq(Questions::getIsChoice, 1);
        IPage<Questions> questionsIPage = questionsMapper.selectPage(p, wrapper);
        List<Questions> records = questionsIPage.getRecords();
        records.stream().forEach(c->{
            LambdaQueryWrapper<SubjectsDirectorys> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(SubjectsDirectorys::getId,c.getCatalogID());
            SubjectsDirectorys subjectsDirectorys = subjectsDirectorysMapper.selectOne(wrapper1);
            Companys companys = companysMapper.selectById(c.getEnterpriseID());
            Subjects subjects = subjectsMapper.selectById(c.getSubjectID());
            c.setCatalog(subjectsDirectorys.getDirectoryName());
            c.setCreator(user.getUsername());
            c.setEnterprise(companys.getShortName());
            c.setSubject(subjects.getSubjectName());
            c.setChkUser(user.getUsername());
        });
        PageResult pageResult = new PageResult((int)questionsIPage.getTotal(),(int)questionsIPage.getSize(),(int)questionsIPage.getPages(),(int)questionsIPage.getCurrent(),records);
        return pageResult;
    }

    @Override
    public PageResult findPageRandoms(Integer page, Integer pagesize, String keyword) {
        IPage<Answer> p = new Page<>(page,pagesize);
        LambdaQueryWrapper<Answer> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Answer::getId,keyword);
        IPage<Answer> answerIPage = answerMapper.selectPage(p, wrapper);
        PageResult pageResult = new PageResult((int)answerIPage.getTotal(),(int)answerIPage.getSize(),(int)answerIPage.getPages(),(int)answerIPage.getCurrent(),answerIPage.getRecords());
        return pageResult;
    }

    @Override
    public void deleteRandomsById(Integer id) {
        answerMapper.deleteById(id);
    }

    @Override
    public void patchById(Integer id, Integer choiceState) {
        Questions questions = new Questions();
        questions.setId(id);
        questions.setIsChoice(choiceState);
        questionsMapper.updateById(questions);
    }

    @Override
    public void updateCheckById(Integer id, Questions questions) {
        Questions questions1 = new Questions();
        questions1.setId(id);
        questions1.setChkState(questions.getChkState());
        questions1.setChkRemarks(questions.getChkRemarks());
        questionsMapper.updateById(questions1);
    }

    @Transactional
    @Override
    public QuestionsAuditsDto audiOpinions(Integer id, String username) {
        QuestionsAuditsDto questionsAuditsDto = new QuestionsAuditsDto();
        Questions questions = questionsMapper.selectById(id);
        questionsAuditsDto.setQuestionsID(questions.getId());
        questionsAuditsDto.setChkTime(LocalDateTime.now());
        questionsAuditsDto.setOpinion(questions.getRemarks());
        questionsAuditsDto.setChecker(username);
        questionsAuditsMapper.updateById(questionsAuditsDto);
        return questionsAuditsDto;
    }

    @Transactional
    @Override
    public QuestionsRecordsDto setRecords(Integer id, String username) {
        Questions questions = questionsMapper.selectById(id);
        Integer publishState = questions.getPublishState();
        QuestionsRecordsDto questionsRecordsDto = new QuestionsRecordsDto();
        questionsRecordsDto.setSetter(username);
        questionsRecordsDto.setQuestionsID(id);
        questionsRecordsDto.setSetTime(LocalDateTime.now());
        questionsRecordsDto.setOperation(publishState == 0 ? "下架":"上架");
        questionsRecordsMapper.updateById(questionsRecordsDto);
        return questionsRecordsDto;
    }
}
